<template>
  <div class="group-setting-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 表单内容 -->
    <el-form 
      v-else
      ref="groupFormRef" 
      :model="groupForm" 
      :rules="groupFormRules" 
      label-width="150px" 
      class="group-form"
    >
      <div class="form-row">
        <el-form-item label="集团名称" prop="name">
          <el-input v-model="groupForm.title" placeholder="请输入集团名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="集团简称" prop="shortName">
          <el-input v-model="groupForm.shortName" placeholder="请输入集团简称"></el-input>
        </el-form-item> -->
      </div>

      <div class="form-row">
        <el-form-item label="手机号码1" prop="phone">
          <el-input v-model="groupForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
      </div>

 
    
      <div class="form-row">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="groupForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </div>

        
      <div class="form-row">
        <el-form-item label="地址" prop="address">
          <el-input v-model="groupForm.address" placeholder="请输入地址"></el-input>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="微信公众号" prop="wechat_qr_code_file">
          <el-upload
            ref="wechatUploadRef"
            :http-request="customUpload"
            :file-list="wechatFileList"
            :on-success="handleWechatUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleWechatUploadRemove"
            :on-exceed="handleWechatUploadExceed"
            :before-upload="beforeUpload"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            list-type="picture-card"
            class="wechat-upload"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png格式，大小不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </div>

      <div class="form-row">
        <el-form-item label="销售客服" prop="service_qr_code_file">
          <el-upload
            ref="serviceUploadRef"
            :http-request="customServiceUpload"
            :file-list="serviceFileList"
            :on-success="handleServiceUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleServiceUploadRemove"
            :on-exceed="handleServiceUploadExceed"
            :before-upload="beforeUpload"
            :show-file-list="true"
            :limit="1"
            accept="image/*"
            list-type="picture-card"
            class="service-upload"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png格式，大小不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </div>
      
      <!-- <div class="form-row">
        <el-form-item label="系统绑定手机" prop="systemPhone">
          <div class="phone-wrapper">
            <el-input v-model="groupForm.systemPhone" placeholder="请输入系统绑定手机号" disabled></el-input>
            <el-button type="primary" class="change-phone-btn" @click="showPhoneDialog">更改手机号</el-button>
          </div>
        </el-form-item>
      </div>
       -->
      <!-- <div class="form-row" style="width: 30%;">
        <el-form-item label="管理员" prop="admin" >
          <el-input v-model="groupForm.admin" disabled placeholder="请输入管理员账号"></el-input>
        </el-form-item>
      </div>
       -->
      <div class="form-row full-width">
        <el-form-item label="公司介绍" prop="introduction" class="full-width-item">
          <el-input 
            v-model="groupForm.content" 
            type="textarea" 
            :rows="8" 
            placeholder="请输入公司介绍">
          </el-input>
        </el-form-item>
      </div>
      
      <div class="form-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-form>
    
    <!-- 更改手机号弹窗 -->
    <el-dialog
      v-model="phoneDialogVisible"
      title="更改绑定手机"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form 
        ref="phoneFormRef" 
        :model="phoneForm" 
        :rules="phoneFormRules" 
        label-width="120px" 
        class="phone-form"
      >
        
     
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePhoneNumber">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCompanyList, updateCompanyInfo, addCompanyInfo, queryCompanyInfo } from '@/api/modules/company'

// 表单引用
const groupFormRef = ref(null)
const wechatUploadRef = ref(null)
const serviceUploadRef = ref(null)

// 加载状态
const loading = ref(false)

// 文件上传相关
const wechatFileList = ref([])
const serviceFileList = ref([])
const uploadAction = '/api/v1/company-info' // 上传接口地址
const uploadHeaders = ref({
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}` // 从localStorage获取token
})
const uploadData = ref({}) // 上传时的额外数据

// 自定义上传方法，使用PUT请求 - 微信公众号二维码
const customUpload = async (options) => {
  const { file, onSuccess, onError, onProgress } = options
  
  try {
    console.log('开始上传微信公众号二维码:', file)
    
    // 创建FormData对象，只包含文件数据
    const formData = new FormData()
    formData.append('wechat_qr_code_file', file)
    
    // 构建查询参数URL
    const queryParams = new URLSearchParams()
    queryParams.append('title', groupForm.title || '')
    queryParams.append('content', groupForm.content || '')
    queryParams.append('phone', groupForm.phone || '')
    queryParams.append('email', groupForm.email || '')
    queryParams.append('address', groupForm.address || '')
    
    // 如果有公司ID，添加到查询参数中
    if (groupForm.id) {
      queryParams.append('id', groupForm.id)
    }
    
    // 构建完整的请求URL（包含查询参数）
    const url = `/api/v1/company-info?${queryParams.toString()}`
    
    console.log('请求URL:', url)
    console.log('查询参数:', queryParams.toString())
    
    // 发送PUT请求
    const response = await fetch(url, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
        // 注意：不设置Content-Type，让浏览器自动设置multipart/form-data的boundary
      },
      body: formData
    })
    
    console.log('响应状态:', response.status)
    console.log('响应头:', response.headers)
    
    if (response.ok) {
      const result = await response.json()
      console.log('上传成功:', result)
      ElMessage.success('微信公众号二维码上传成功')
      onSuccess(result, file)
    } else {
      const errorText = await response.text()
      console.error('上传失败:', errorText)
      onError(new Error(`上传失败: ${response.status} ${errorText}`), file)
    }
  } catch (error) {
    console.error('上传异常:', error)
    onError(error, file)
  }
}

// 自定义上传方法，使用PUT请求 - 销售客服二维码
const customServiceUpload = async (options) => {
  const { file, onSuccess, onError, onProgress } = options
  
  try {
    console.log('开始上传销售客服二维码:', file)
    
    // 创建FormData对象，只包含文件数据
    const formData = new FormData()
    formData.append('service_qr_code_file', file)
    
    // 构建查询参数URL
    const queryParams = new URLSearchParams()
    queryParams.append('title', groupForm.title || '')
    queryParams.append('content', groupForm.content || '')
    queryParams.append('phone', groupForm.phone || '')
    queryParams.append('email', groupForm.email || '')
    queryParams.append('address', groupForm.address || '')
    
    // 如果有公司ID，添加到查询参数中
    if (groupForm.id) {
      queryParams.append('id', groupForm.id)
    }
    
    // 构建完整的请求URL（包含查询参数）
    const url = `/api/v1/company-info?${queryParams.toString()}`
    
    console.log('销售客服请求URL:', url)
    console.log('销售客服查询参数:', queryParams.toString())
    
    // 发送PUT请求
    const response = await fetch(url, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
        // 注意：不设置Content-Type，让浏览器自动设置multipart/form-data的boundary
      },
      body: formData
    })
    
    console.log('销售客服响应状态:', response.status)
    console.log('销售客服响应头:', response.headers)
    
    if (response.ok) {
      const result = await response.json()
      console.log('销售客服上传成功:', result)
      ElMessage.success('销售客服二维码上传成功')
      onSuccess(result, file)
    } else {
      const errorText = await response.text()
      console.error('销售客服上传失败:', errorText)
      onError(new Error(`上传失败: ${response.status} ${errorText}`), file)
    }
  } catch (error) {
    console.error('销售客服上传异常:', error)
    onError(error, file)
  }
}

// 表单数据
const groupForm = reactive({
  id: null, // 公司ID，用于判断是新增还是更新
  title: '', // 公司名称
  content: '', // 公司介绍
  phone: '', // 手机号码
  email: '', // 邮箱
  address: '', // 地址
  wechat_qr_code_file: null, // 微信公众号二维码文件
  service_qr_code_file: null, // 销售客服二维码文件
  name: '',
  shortName: '',
  systemPhone: '',
  admin: '',
  introduction: ''
})

// 表单校验规则
const groupFormRules = {
  // name: [
  //   { required: true, message: '请输入集团名称', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  // ],
  // shortName: [
  //   { required: true, message: '请输入集团简称', trigger: 'blur' },
  //   { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  // ],
  // systemPhone: [
  //   { required: true, message: '请输入系统绑定手机号', trigger: 'blur' },
  //   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  // ],
  // admin: [
  //   { required: true, message: '请输入管理员账号', trigger: 'blur' }
  // ]
}

// 文件上传相关方法
// 上传前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 微信公众号二维码上传成功回调
const handleWechatUploadSuccess = (response, file, fileList) => {
  console.log('微信公众号二维码上传成功:', response, file)
  // 保存文件信息到表单数据
  groupForm.wechat_qr_code_file = file.raw
  // 移除重复的成功提示，因为自定义上传方法中已经提示了
}

// 销售客服二维码上传成功回调
const handleServiceUploadSuccess = (response, file, fileList) => {
  console.log('销售客服二维码上传成功:', response, file)
  // 保存文件信息到表单数据
  groupForm.service_qr_code_file = file.raw
  // 移除重复的成功提示，因为自定义上传方法中已经提示了
}

// 文件上传失败回调
const handleUploadError = (error, file, fileList) => {
  console.error('文件上传失败:', error)
  ElMessage.error('文件上传失败，请重试')
}

// 微信公众号二维码删除回调
const handleWechatUploadRemove = (file, fileList) => {
  console.log('删除微信公众号二维码:', file)
  groupForm.wechat_qr_code_file = null
  ElMessage.success('已删除微信公众号二维码')
}

// 销售客服二维码删除回调
const handleServiceUploadRemove = (file, fileList) => {
  console.log('删除销售客服二维码:', file)
  groupForm.service_qr_code_file = null
  ElMessage.success('已删除销售客服二维码')
}

// 微信公众号上传超出限制回调
const handleWechatUploadExceed = (files, fileList) => {
  console.log('微信公众号上传超出限制:', files, fileList)
  ElMessage.warning('微信公众号只能上传一张图片，请先删除现有图片再上传新图片')
}

// 销售客服上传超出限制回调
const handleServiceUploadExceed = (files, fileList) => {
  console.log('销售客服上传超出限制:', files, fileList)
  ElMessage.warning('销售客服只能上传一张图片，请先删除现有图片再上传新图片')
}

// 提交表单
const submitForm = async () => {
  if (!groupFormRef.value) return
  
  await groupFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 统一使用PUT请求保存所有数据（包括文本和文件）
        const formData = new FormData()
        
        // 添加文本数据
        formData.append('title', groupForm.title || '')
        formData.append('content', groupForm.content || '')
        formData.append('phone', groupForm.phone || '')
        formData.append('email', groupForm.email || '')
        formData.append('address', groupForm.address || '')
        
        // 如果有公司ID，添加到表单数据中
        if (groupForm.id) {
          formData.append('id', groupForm.id)
        }
        
        // 添加文件数据（如果存在）
        if (groupForm.wechat_qr_code_file) {
          formData.append('wechat_qr_code_file', groupForm.wechat_qr_code_file)
        }
        if (groupForm.service_qr_code_file) {
          formData.append('service_qr_code_file', groupForm.service_qr_code_file)
        }
        
        // 构建查询参数URL（根据API文档要求，文本参数作为查询参数）
        const queryParams = new URLSearchParams()
        queryParams.append('title', groupForm.title || '')
        queryParams.append('content', groupForm.content || '')
        queryParams.append('phone', groupForm.phone || '')
        queryParams.append('email', groupForm.email || '')
        queryParams.append('address', groupForm.address || '')
        
        if (groupForm.id) {
          queryParams.append('id', groupForm.id)
        }
        
        const url = `/api/v1/company-info?${queryParams.toString()}`
        
        console.log('保存公司信息:', {
          url,
          hasWechatFile: !!groupForm.wechat_qr_code_file,
          hasServiceFile: !!groupForm.service_qr_code_file
        })
        
        // 发送PUT请求
        const response = await fetch(url, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
          },
          body: formData
        })
        
        if (response.ok) {
          const result = await response.json()
          console.log('保存成功:', result)
          ElMessage.success('保存成功')
          
          // 如果返回了ID，保存到表单数据中
          if (result.id && !groupForm.id) {
            groupForm.id = result.id
          }
        } else {
          const errorText = await response.text()
          console.error('保存失败:', errorText)
          ElMessage.error(`保存失败: ${response.status} ${errorText}`)
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请稍后重试')
      }
    } else {
      console.log('表单校验失败', fields)
      return false
    }
  })
}

// 获取集团信息
const fetchGroupInfo = async () => {
  try {
    loading.value = true
    
    // 调用 API 获取公司信息
    const response = await getCompanyList()
    console.log(response,'response===============333333333')
    
    // 检查响应数据
    if (response ) {
      console.log('获取到的完整响应数据:', response)
      
      // 填充表单数据
        groupForm.id = response.id || null // 保存公司ID
        groupForm.title = response.title || ''
        groupForm.phone = response.phone || ''
        groupForm.email = response.email || ''
        groupForm.address = response.address || ''
        groupForm.content = response.content || ''
        
        // 清空文件列表，准备重新填充
        wechatFileList.value = []
        serviceFileList.value = []
        
        // 处理微信公众号二维码
        const wechatQrCodeUrl = response.wechat_qr_code_url || response.wechatQrCodeUrl || response.wechat_qr_code
        console.log('微信公众号二维码URL:', wechatQrCodeUrl)
        if (wechatQrCodeUrl) {
          // 使用nextTick和延迟确保DOM更新后再设置文件列表
          nextTick(() => {
            setTimeout(() => {
              wechatFileList.value = [{
                name: '微信公众号二维码',
                url: wechatQrCodeUrl,
                status: 'success',
                uid: Date.now() // 添加唯一ID
              }]
              console.log('设置微信公众号文件列表:', wechatFileList.value)
            }, 100) // 延迟100ms确保组件完全渲染
          })
        }
        
        // 处理销售客服二维码
        const serviceQrCodeUrl = response.service_qr_code_url || response.serviceQrCodeUrl || response.service_qr_code
        console.log('销售客服二维码URL:', serviceQrCodeUrl)
        if (serviceQrCodeUrl) {
          // 使用nextTick和延迟确保DOM更新后再设置文件列表
          nextTick(() => {
            setTimeout(() => {
              serviceFileList.value = [{
                name: '销售客服二维码',
                url: serviceQrCodeUrl,
                status: 'success',
                uid: Date.now() + 1 // 添加唯一ID
              }]
              console.log('设置销售客服文件列表:', serviceFileList.value)
            }, 100) // 延迟100ms确保组件完全渲染
          })
        }
    } else {
      console.log('响应数据为空或undefined')
    }
  } catch (error) {
 
    ElMessage.error('获取公司信息失败，请稍后重试')
    
    // 如果接口调用失败，使用默认数据
    const defaultData = {
      title: '',
      phone: '',
      email: '',
      address: '',
      name: '',
      shortName: '',
      systemPhone: '158****8958',
      admin: 'Adminstrators',
      introduction: ''
    }
    Object.assign(groupForm, defaultData)
  } finally {
    loading.value = false
  }
}

// 手机号变更相关
const phoneDialogVisible = ref(false)
const phoneFormRef = ref(null)
const phoneForm = reactive({
  newPhone: '',
  verificationCode: ''
})

// 手机号验证规则
const phoneFormRules = {
  newPhone: [
    { required: true, message: '请输入新手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 验证码发送相关
const countDown = ref(0)
const isSendingCode = ref(false)
let timer = null

// 发送验证码按钮文本
const sendCodeBtnText = computed(() => {
  if (countDown.value > 0) {
    return `重新发送(${countDown.value}s)`
  }
  return '发送验证码'
})

// 显示手机号修改弹窗
const showPhoneDialog = () => {
  phoneForm.newPhone = ''
  phoneForm.verificationCode = ''
  phoneDialogVisible.value = true
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!phoneForm.newPhone) {
    ElMessage.warning('请先输入新手机号')
    return
  }
  
  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phoneForm.newPhone)) {
    ElMessage.warning('请输入正确的手机号码')
    return
  }
  
  // 设置倒计时
  countDown.value = 60
  isSendingCode.value = true
  
  // 模拟发送验证码
  ElMessage.success(`验证码已发送至手机 ${phoneForm.newPhone}`)
  
  // 开始倒计时
  timer = setInterval(() => {
    countDown.value--
    if (countDown.value <= 0) {
      clearInterval(timer)
      isSendingCode.value = false
    }
  }, 1000)
}

// 更新手机号
const updatePhoneNumber = async () => {
  if (!phoneFormRef.value) return
  
  await phoneFormRef.value.validate((valid, fields) => {
    if (valid) {
      // 模拟更新手机号
      setTimeout(() => {
        // 手机号显示格式 158****8958
        const phonePrefix = phoneForm.newPhone.substring(0, 3)
        const phoneSuffix = phoneForm.newPhone.substring(7)
        groupForm.systemPhone = `${phonePrefix}****${phoneSuffix}`
        
        ElMessage.success('手机号更改成功')
        phoneDialogVisible.value = false
      }, 500)
    } else {
      console.log('表单校验失败', fields)
      return false
    }
  })
}

// 清除定时器
const clearTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 页面卸载时清除定时器
onMounted(() => {
  // 初始化文件列表
  wechatFileList.value = []
  serviceFileList.value = []
  
  // 获取公司信息
  fetchGroupInfo()
})

// 组件卸载前清理资源
const onBeforeUnmount = () => {
  clearTimer()
}
</script>

<style lang="scss" scoped>
.group-setting-container {
  .loading-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
  }
  
  .group-form {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    
    .form-row {
      display: flex;
      margin-bottom: 20px;
      
      .el-form-item {
        flex: 1;
        margin-right: 20px;
        
        &:last-child {
          margin-right: 0;
        }
      }
      
      &.full-width {
        display: block;
        
        .full-width-item {
          width: 100%;
        }
      }
      
      .phone-wrapper {
        display: flex;
        align-items: center;
        
        .el-input {
          flex: 1;
        }
        
        .change-phone-btn {
          margin-left: 10px;
          white-space: nowrap;
        }
      }
    }
    
    .form-footer {
      margin-top: 30px;
      text-align: center;
    }
  }
  
  .phone-form {
    padding: 10px 20px;
    
    .verification-code-wrapper {
      display: flex;
      align-items: center;
      
      .el-input {
        flex: 1;
      }
      
      .send-code-btn {
        margin-left: 10px;
        white-space: nowrap;
      }
    }
  }
  
  // 微信公众号上传组件样式
  .wechat-upload {
    :deep(.el-upload--picture-card) {
      width: 148px;
      height: 148px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.2s;
      
      &:hover {
        border-color: #409eff;
      }
    }
    
    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 148px;
      height: 148px;
      border-radius: 6px;
    }
    
    :deep(.el-upload__tip) {
      color: #999;
      font-size: 12px;
      margin-top: 8px;
      text-align: center;
    }
  }
  
  // 销售客服上传组件样式
  .service-upload {
    :deep(.el-upload--picture-card) {
      width: 148px;
      height: 148px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.2s;
      
      &:hover {
        border-color: #409eff;
      }
    }
    
    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 148px;
      height: 148px;
      border-radius: 6px;
    }
    
    :deep(.el-upload__tip) {
      color: #999;
      font-size: 12px;
      margin-top: 8px;
      text-align: center;
    }
  }
}
</style> 